
const chokidar = require('chokidar')
const fs = require('fs');

let watcher = null
let ready = false
let watch = function (filepath) {
  // 文件新增时
  function addFileListener(path_) {
    if (ready) {
      console.log('文件', path_, '被添加了')
      needUpdateLib(path_, 'update')
    }
  }
  function addDirecotryListener(path_) {
    if (ready) {
      console.log('目录', path_, '被添加了')
      needUpdateLib(path_, 'update')
    }
  }

  // 文件内容改变时
  function fileChangeListener(path_) {
    console.log('文件', path_, '已经修改')
    needUpdateLib(path_, 'update')
  }

  // 删除文件
  function fileRemovedListener(path_) {
    console.log('文件', path_, '被删除了')
    needUpdateLib(path_, 'remove')
  }

  // 删除目录时
  function directoryRemovedListener(path_) {
    // ./lib_mb/build/pcom
    // E:\work\codewarehouse\vue-lib-factory\lib_mb\dev\pcom
    if (path_.indexOf('vue-lib-factory') == -1) {
      path_ = path_.replace('./', '')
      path_ = path_.replace('/', '\\')
    } else {
      console.log('lsjdlaj', path_.split('vue-lib-factory\\')[1])
      path_ = path_.split('vue-lib-factory\\')[1]
    }
    console.info('目录', path_, '被删除了')
    needUpdateLib(path_, 'remove')

  }

  if (!watcher) {
    watcher = chokidar.watch(filepath)
  }
  watcher
    .on('add', addFileListener)
    .on('addDir', addDirecotryListener)
    // .on('change', fileChangeListener)
    .on('unlink', fileRemovedListener)
    .on('unlinkDir', directoryRemovedListener)
    .on('error', function (error) {
      console.info('发生了错误：', error);
    })
    .on('ready', function () {
      console.info('准备监听');
      ready = true
    })
}
watch(['./lib_mb/dev', './lib_pc/dev'])
// watch(['./lib_mb/dev','./lib_pc/dev/kfzx'])

let wait = true;
let libarr;
function needUpdateLib(path_, state,basece = 4) {
  path_ = path_.replace(/\s+/g,'')   // 去掉空格
  libarr = fs.readFileSync('./needUpdateLibs.txt', 'utf-8')
  libarr = libarr ? libarr.split(',') : []
  let file = path_.split('\\')
  let filePath = `./${file[0]}/${file[1]}/${file[2]}`
  // needUpdateLibs 是否无
  if (libarr.indexOf(filePath) == -1) {
    // 判断是否操作的是根目录
    if (file.length === 3) {
      // 是否是删除操作
      if (state == 'remove') {
        // 删除build和preview中的文件
        libarr.splice(libarr.indexOf(filePath), 1)
        deleteDir('./' + file[0] + '/' + 'build' + '/' + file[2])
      } else {
        libarr.push(filePath)
      }
    } else {
      if (state != 'remove') {
        libarr.push(filePath)
      } else {
        // 单单删除一个非根目录的不做操作
      }
    }
  } else {
    if (file.length == 3) {
      if (state == 'remove') {
        libarr.splice(libarr.indexOf(filePath), 1)
        // 删除build和preview中的文件
        deleteDir('./' + file[0] + '/' + 'build' + '/' + file[2])
      }
    }
  }
  
  fs.writeFile('./needUpdateLibs.txt', libarr, () => {
    console.log('写入'+libarr+'成功')
  })
}

function tips(content) {
  console.log(content)
}

// 删除非空文件
function deleteDir(path) {
  if( fs.existsSync(path) ) {
      fs.readdirSync(path).forEach(function(file) {
          let curPath = path + "/" + file;
          if(fs.statSync(curPath).isDirectory()) { // recurse
              deleteDir(curPath);
          } else { // delete file
              fs.unlinkSync(curPath);
          }
      });
      fs.rmdirSync(path);
  }
};
